package com.liuzhilong.infrastructure.middleware.elasticsearch.infastructure.book.assembler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.liuzhilong.infrastructure.middleware.elasticsearch.entity.Book;
import lombok.SneakyThrows;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.util.Date;

/**
 *
 */
public class BookESAssembler {

    @SneakyThrows
    public static XContentBuilder xContentBuilderBook(Book book){
        Preconditions.checkNotNull(book);
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.field("user", "kimchy");
            builder.field("postDate", new Date());
            builder.field("message", "trying out Elasticsearch");
        }
        builder.endObject();
        return builder;
    }

    @SneakyThrows
    public static String bookToJson(Book book){
        Preconditions.checkNotNull(book);
        return new ObjectMapper().writeValueAsString(book);
    }
    @SneakyThrows
    public static Book jsonToBook(String json){
        Preconditions.checkNotNull(json);
        return new ObjectMapper().readValue(json,Book.class);
    }
}
